﻿using System;
using System. Collections. Generic;
using System. Linq;
using System. Windows;
using System. Windows. Data;
using System. Windows. Media;
using System. Windows. Media. Imaging;
using System. Xml. Linq;
using Microsoft. Phone. Controls;
using Microsoft. Phone. Shell;
using Microsoft. Phone. Tasks;
using NextApp. WP7. AppConfig;
using NextApp. WP7. Models;
using NextApp. WP7. View. Controls;
using WP7_WebLib. HttpPost;
using NextApp. WP7. Util;
using NextApp. WP7. Cache. NextApp;

namespace NextApp. WP7. View
{
    public partial class AddPost : PhoneApplicationPage
    {
        #region Initialize
        public AddPost( )
        {
            InitializeComponent( );
			this. PrepareToOrientation( );
            this. ApplicationTitle. Text = Config. Instance. blog_title;
            this. Loaded += new RoutedEventHandler(AddPost_Loaded);
        }
        private int catalog { get; set; }
        protected override void OnNavigatedTo(System. Windows. Navigation. NavigationEventArgs e)
        {
            Util. Tool. CheckAppBar(this);
            this. LoadCatalogsToListPicker( );
            base. OnNavigatedTo(e);
        }
        private void LoadCatalogsToListPicker( )
        {
            if ( DataSingleton.Instance.catalogs != null )
            {
                DataSingleton. Instance. catalogs. ForAll(c => this. ddl_Catalog. Items. Add(c));
            }
        }
        #endregion

        #region 选择图片 以及收集图片信息
        private PhotoChooserTask photoChooser;
        private CameraCaptureTask cameraCapture;
        private void btn_ChosePic_Click(object sender, RoutedEventArgs e)
        {
            this. border_SelectImgs. Visibility = this. border_SelectImgs. Visibility == Visibility. Visible ?
                Visibility. Collapsed : Visibility. Visible;
        }
        private void btn_SelectImgFromLib_Click(object sender, RoutedEventArgs e)
        {
            this. photoChooser = new PhotoChooserTask { ShowCamera = true };
            this. photoChooser. Completed += new EventHandler<PhotoResult>(photoChooser_Completed);
            this. photoChooser. Show( );
        }
        private void btn_Camera_Click(object sender, RoutedEventArgs e)
        {
            this. cameraCapture = new CameraCaptureTask( );
            this. cameraCapture. Completed += new EventHandler<PhotoResult>(photoChooser_Completed);
            this. cameraCapture. Show( );
        }
        private void photoChooser_Completed(object sender, PhotoResult e)
        {
            if ( e. TaskResult == TaskResult. OK )
            {
                BitmapImage bitmap = new BitmapImage( );
                bitmap. SetSource(e. ChosenPhoto);
                //新增加一个 Image
                ImgWithClose img = new ImgWithClose
                {
                    Source = bitmap,
                    Margin = new Thickness(0),
                    Width = 180,
                    Height = 180,
                    Stretch = Stretch. UniformToFill,
                    PhotoInfo = e,
                };
                img. Close += (s1, e1) =>
                {
                    ImgWithClose old = s1 as ImgWithClose;
                    if ( old != null )
                    {
                        this. wrapPanel_Imgs. Children. Remove(old);
                    }
                };
                this. wrapPanel_Imgs. Children. Add(img);
            }
        }
        private PhotoResult[ ] GatherAllImgs
        {
            get
            {
                return this. wrapPanel_Imgs. Children. Select(c => ( c as ImgWithClose ). PhotoInfo). ToArray( );
            }
        }
        #endregion

        #region 发表文章
        private void btn_Post_Pub_Click(object sender, RoutedEventArgs e)
        {
            StandardPostClient client = new StandardPostClient { UserAgent = Config. Instance. Http_User_Agent };
            client. DownloadStringCompleted += (s, e1) =>
            {
                if ( e1. Error != null )
                {
                    MessageBox. Show("发表文章失败", "网络错误", MessageBoxButton. OK);
                    return;
                }
				XElement x;
				try
				{
					x = XElement. Parse(e1. Result). Element("result");
				}
				catch ( Exception )
				{
					return;
				}
                ApiError _error = new ApiError
                {
                    errorCode = x. Element("errorCode"). Value. ToInt32( ),
                    errorMessage = x. Element("errorMessage"). Value,
                };
                this. ProgressIndicatorIsVisible = false;
                //分析错误代码
                this. DisplayResult_AddPost(_error);
            };
            PhotoResult[ ] photos = this. GatherAllImgs;
            Dictionary<string, object> parameters = new Dictionary<string, object>
            {
                {"catalog", (this.ddl_Catalog.SelectedItem as Catalog).id},
                {"title", txt_title.Text.Trim()},
                {"body", txt_body.Text.Trim()},
                {"tag", txt_tags.Text.Trim()},
            };
            if ( NextAppSingleton.Instance.url_post_pub.IsNotNullOrWhitespace() )
            {
                client. UploadFilesToRemoteUrl(Config. Instance. GetApi(NextAppSingleton. Instance. url_post_pub),
                                                                    photos == null ? null : photos. Select(p => p. OriginalFileName). ToArray( ),
                                                                    photos == null ? null : photos. Select(p => p. ChosenPhoto). ToArray( ),
                                                                    parameters,
                                                                    Config. Instance. Cookie,
                                                                    true);
                this. ProgressIndicatorIsVisible = true;
            }
        }

        private void DisplayResult_AddPost(ApiError _error)
        {
            if ( _error.errorCode > 0 )
            {
                MessageBox. Show("文章发表成功");
                return;
            }
            switch ( _error.errorCode )
            {
                case 0:
                    if ( MessageBox.Show("您还未登录, 请先登陆", "发表文章失败", MessageBoxButton.OKCancel) == MessageBoxResult.OK )
                    {
                        this. NavigationService. Navigate(new Uri("/View/Login.xaml", UriKind. Relative));
                    }
                    break;
                case -1:
                    MessageBox. Show("文章发表失败, 其他错误");
                    break;
                case -2:
                    MessageBox. Show("文章发表失败, 没有发表权限");
                    break;
                default:
                    MessageBox. Show(_error. errorMessage);
                    break;
            }
        }
        #endregion

        #region 进度条处理
        void AddPost_Loaded(object sender, RoutedEventArgs e)
        {
            SystemTray. ProgressIndicator = new ProgressIndicator( );
            SystemTray. ProgressIndicator. Text = "正在发表";

            Binding bindingData;
            bindingData = new Binding("ProgressIndicatorIsVisible");
            bindingData. Source = this;
            BindingOperations. SetBinding(SystemTray. ProgressIndicator, ProgressIndicator. IsVisibleProperty, bindingData);
            BindingOperations. SetBinding(SystemTray. ProgressIndicator, ProgressIndicator. IsIndeterminateProperty, bindingData);
        }
        public static readonly DependencyProperty ProgressIndicatorIsVisibleProperty =
                        DependencyProperty. Register("ProgressIndicatorIsVisible",
                        typeof(bool),
                        typeof(AddPost),
                        new PropertyMetadata(false));
        public bool ProgressIndicatorIsVisible
        {
            get { return ( bool )GetValue(ProgressIndicatorIsVisibleProperty); }
            set { SetValue(ProgressIndicatorIsVisibleProperty, value); }
        }
        #endregion

        #region 登入注销处理
        //登入
        private void menuItem_Login_Click(object sender, EventArgs e)
        {
            Util. Tool. Login( );
        }

        //注销
        private void menuItem_Logout_Click(object sender, EventArgs e)
        {
            Util. Tool. Logout( );
            Util. Tool. CheckAppBar(this);
            if ( this.NavigationService.CanGoBack )
            {
                this. NavigationService. GoBack( );
            }
        }
        #endregion

        #region 解决ListPicker在ScrollViewer中的问题 无法激活的问题 以下代码不需要任何修改
        public bool isListPickerClosed = true;
        private void ddl_Catalog_Tap(object sender, System. Windows. Input. GestureEventArgs e)
        {
            ListPicker lp = sender as ListPicker;
            if ( isListPickerClosed )
            {
                if ( lp. ListPickerMode == ListPickerMode. Normal )
                {
                    lp. Open( );
                }
                isListPickerClosed = false;
            }
            else
            {
                isListPickerClosed = true;
            }
        }
        #endregion
    }
}